<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\ShopUserCategory;
use app\admin\model\OperationTask;
use app\admin\model\Shop;
use app\admin\model\User;
use app\admin\model\DistributeTask as DistributeTaskModer;
use app\admin\model\Withdraw;
use app\admin\model\DistributeTaskLog;
use app\admin\model\PayConfig;
use app\admin\model\DistributeTaskCopyLog;
use app\admin\model\Article;
use app\admin\model\DistributeTaskInvite;
use app\admin\model\Order;
use app\admin\model\Product;
use app\admin\model\UserOrder;
use getui\GeTui;
use addons\shopro\library\AdapayService;
use GuzzleHttp\Promise\Is;
use think\Db;
use think\Log;
use think\Exception;
use think\Session;

class DistributeTask extends Api
{
	protected $noNeedLogin = ['notifyx','question','getIsTc'];
	protected $appid;
	protected $secret;

	public function _initialize(){
		$action = request()->action();
		$ignore = array('host','accept','content-length','content-type');
		$headers = array();
		if($this->request->request('token')){
			$headers['token'] = $this->request->request('token');
		}else{
			foreach($_SERVER as $key=>$value){
				if(substr($key, 0, 5)==='HTTP_'){
					$key = substr($key, 5);
					$key = str_replace('_', ' ', $key);
					$key = str_replace(' ', '-', $key);
					$key = strtolower($key);
					if(!in_array($key, $ignore)){
						$headers[$key] = $value;
					}
				}
			}
		}
		if(empty($headers['token']) && in_array($action,$this->noNeedLogin)){
			//当未传token并且控制器可不不传token情况下不需要验证登录
		}else{
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
            if($this->user['status'] != 1){
                $this->error('账号异常');
            }
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
	}


    //获取任务列表
    public function list(){
        $PayConfig = get_task_config();
        //查看任务总数
        $sum = DistributeTaskModer::whereTime('receive_time', 'today')->where(['status'=>1])->count();
        if($sum >= $PayConfig['yx_num']){
            $list = [];
        }else{
            $arr = [];
            $time = strtotime(date('Y-m-d',time()))-1;
            //当天任务
            $is_new_task = []; 
            $list = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>1])->whereTime('receive_time', 'today')->group('type')->select();
            if($list){
                foreach ($list as $v) {
                    $arr[] = $v;
                    $is_new_task[$v['type']] = 1;
                }
            }
            //之前任务
            $list = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>['in',[0,1,-1]],'receive_time' => ['<', $time]])->group('type')->select();
            if($list){
                foreach ($list as $v) {
                    $item = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>['in',[0,1,-1],'type'=>$v['type']],'receive_time' => ['<', $time]])->select();
                    foreach ($item as $value) {
                        $arr[] = $value;
                    }
                }
            }
            //判断今天是否已经接取了任务   如今天已经接取了任务  则不显示新任务   如未接取新任务  则暂时一个新任务
            $list_1 = DistributeTaskModer::where(['user_id'=>0,'character_type'=>$this->user['character_type'],'status'=>0])->group('type')->select();
            if($list_1){    
                foreach ($list_1 as $v) {
                    if(empty($is_new_task[$v['type']])){
                        $arr[] = $v;
                    }
                    // $res = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>['in',[0,1,-1]],'task_type'=>$v['task_type'],'character_type'=>$this->user['character_type']])->find();
                    // if(!$res){
                    //     $arr[] = $v;
                    // }
                }
            }
            if($arr){
                foreach ($arr as &$info) {
                    if($info['task_status'] == 'pinglun' || $info['task_status'] == 'comment_num'){
                        $info['priceName'] = '¥0.50';
                    }else{

                        if($info['type'] != '余享小红书'){
                            $info['priceName'] = '¥2.00~¥3.00';
                        }else{
                            $info['priceName'] = '¥0~¥3.00';
                        }
                    }
                    $info['time1'] = 0;
                    if($info['status'] == 1){ //已领取状态
                        //判断该用户是否已回传链接
                        $t = time()-$info['receive_time'];
                        if(!$info['user_content']){
                            if($t > 3600){ //已经超时更新订单状态
                                DistributeTaskModer::where(['id'=>$info['id']])->update(['status'=>-2]);
                                $info['status'] = 0;
                            }else{
                                $info['time1'] = 3600 - $t;
                            }
                        }else{
                            if(!$info['user_imgs']){
                                if($t >  (3600*36)){ //已经超时更新订单状态
                                    DistributeTaskModer::where(['id'=>$info['id']])->update(['status'=>-2]);
                                    $info['status'] = 0;
                                }else{
                                    $info['time1'] = (3600*36) - $t;
                                }
                            }
                        }
                    }
                }
            }
        }
      
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $wc_list = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>3])->limit(($page-1)*$pagesize,$pagesize)->select();

        $dsh_list = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>2])->limit(($page-1)*$pagesize,$pagesize)->select();
        $this->success('操作成功',['list'=>$arr,'wc_list'=>$wc_list,'dsh_list'=>$dsh_list,'task_price'=>User::where(['id'=>$this->user['id']])->value('task_price')]);
    }

    //获取邀请用户信息
    public function taskInviteList(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $where = [
            'user_id'=>$this->user['id']            
        ];
        $list = DistributeTaskInvite::where($where)->limit(($page-1)*$pagesize,$pagesize)->order('id desc')->select();
        foreach ($list as &$v) {
            $user = User::where(['id'=>$v['invite_id']])->find();
            $v['avatar'] = $user['avatar'];
            $v['nickname'] = $user['nickname'];
            $v['add_time'] = date('Y-m-d',$v['add_time']);
        }
        $list_count = DistributeTaskInvite::where($where)->count();
        $where['status']=1;
        $arr = [
            'list'=>$list,
            'yx_count'=>DistributeTaskInvite::where($where)->count(),
            'list_count'=>$list_count,
            'price_sum'=>DistributeTaskInvite::where($where)->sum('price')
        ];
        $this->success('操作成功',$arr);
    }
    
    //邀请团长
    public function add_distribute_invite(){
        $task_user_id = $this->request->request('task_user_id',0);
        if($task_user_id && $this->user['is_task'] == 0){
            //查询该用户是否已经是团长了
            User::where(['id'=>$this->user['id']])->update(['is_task'=>-1]);
            // User::where(['id'=>$this->user['id']])->update(['is_task'=>1,'task_time'=>time()]);
            $arr = [
                'user_id'=>$task_user_id,
                'invite_id'=>$this->user['id'],
                'add_time'=>time()
            ];
            DistributeTaskInvite::insert($arr);
        }
    }
    
    public function is_task_subscription(){
        $type = $this->request->request('type',0);
        if($type == 0){
            User::where(['id'=>$this->user['id']])->update(['is_task_subscription'=>1]);
        }elseif($type == 1){
            User::where(['id'=>$this->user['id']])->update(['is_always_task_subscription'=>1]);
        }
    }
    //首页小红书任务列表
    public function taskList(){
        //查询用户信息  如果是新人用户则显示is_new_user=1的任务  否则显示is_new_user=0的任务
        if($this->user['task_status'] == -1){
            $this->success('操作成功',[]);
        }
        $where = [
            'user_id'=>0,
            'character_type'=>$this->user['character_type'],
            'status'=>0,
            'task_type'=>1,
            //'is_new_user'=>0
        ];
        // if($this->user['task_price'] == 0){  //判断是否是新人
        //     $is_new_user = DistributeTaskLog::where(['type'=>2,'user_id'=>$this->user['id']])->find();
        //     if(!$is_new_user){
        //         $where['is_new_user'] = 1;
        //     }
        // }
        //打开就是只能接相对应类别任务
        /* $ids = ShopUserCategory::where(['user_id'=>$this->user['id']])->column('category_id');
        if($ids){
            $shop_names = Shop::where(['category_id'=>['in',$ids]])->column('name');
            if($this->user['is_admin'] == 1){
                $shop_names[] = '苏拉科技';
            }
            $where['type'] = ['in',$shop_names];
        }else{
            if($this->user['is_admin'] == 0){
                $where['type'] = ['neq','苏拉科技'];
            }
        } */
        if($this->user['is_material'] ==1){
            $where['task_type'] = 5;
        }else{
            $category_arr = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>['in',[1,2,3]],'category'=>['neq',0]])->whereTime('receive_time', '-7 days')->column('category');
            if($category_arr){
                $where['category'] = ['not in',$category_arr];
            }
        }
        $sum = DistributeTaskModer::whereTime('receive_time', 'today')->where(['status'=>1,'type'=>'余享小红书'])->count();
        $list = DistributeTaskModer::where($where)->group('type')->select();
        

        $arr = [];
        $PayConfig = get_task_config();
        if($list){
            foreach ($list as &$v) {
                if($v['type'] == '余享小红书' && $this->user['is_accept_yx'] == '-1'){
                    continue;
                }
                if($v['task_status'] == 'pinglun' || $v['task_status'] == 'comment_num'){
                    $v['priceName'] = '¥0.50';
                }else{
                    if($v['type'] != '余享小红书'){
                        $v['priceName'] = '¥2.00~¥3.00';
                    }else{
                        $v['priceName'] = '¥0~¥3.00';
                    }
                }
                //判断该任务是否存在指定省的情况
                if($v['province'] && $v['province'] != $this->user['province']){
                    //查询该类型任务是否存在指定省的  如果有则还是显示  如果没有则不显示
                    $res = DistributeTaskModer::where(['user_id'=>0,'character_type'=>$this->user['character_type'],'status'=>0,'type'=>$v['type'],'province'=>['in',['',$this->user['province']]]])->select();
                    if(!$res){
                        //没有可以接的任务
                        continue;
                    }
                }
                $info = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>1,'character_type'=>$this->user['character_type'],'type'=>$v['type'],'task_type'=>1])->whereTime('receive_time', 'today')->find();
                
              
                    //if($v['type'] != '米兰租车'){
                        if($v['type'] == '余享小红书'){
                            // if($where['is_new_user'] == 1){
                            //     $arr[] = $v;
                            // }else
                            if($sum <  $PayConfig['yx_num'] && !$info){
                                //查询今日是否结果该任务
                                $arr[] = $v;
                            }
                        }elseif(!$info){
                            $arr[] = $v;
                        }elseif($info && $info['type'] == '电事聚小红书' && $info['receive_time'] < time()-(3600*5)){
                            $arr[] = $v;
                        }
                    //}
               
            }
        }
        $this->success('操作成功',$arr);
    }

    //首页评论任务列表
    public function taskCommentList(){
        if($this->user['task_status'] == -1){
            $this->success('操作成功',[]);
        }
        $list = DistributeTaskModer::where(['user_id'=>0,'status'=>0,'task_type'=>4])->group('type')->select();
        $arr = [];
        if($list){
            foreach ($list as &$v) {
                $v['priceName'] = '¥0.50';
                $info = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>1,'task_type'=>4])->whereTime('receive_time', 'today')->find();
                if(!$info){
                    $arr[] = $v;
                }
            }
        }
        $this->success('操作成功',$arr);
    }

    //领取任务
    public function getTask(){
        $type = $this->request->request('type','余享小红书');
        $task_type = $this->request->request('task_type',1);
        //判断当前接单时间
        $time = strtotime(date('Y-m-d',time()));
        if(time()>$time && time() < ($time+6*3600)){
            $this->error('请在每天的早上06:00之后接单');
        }
        if($this->user['task_status'] == -1){
            $this->error('您已被冻结接单资格，请更换账号或联系客服');
        }

        if($task_type == 1){
            //判断用户已经领取的了多少个任务
            $PayConfig = get_task_config();
            $count = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>['in',[1,2,-1]]])->whereTime('receive_time', 'today')->count();
            if($count >= $PayConfig['user_get_task_num']){
                $this->error('您当天领取任务数量已达到上限,请明日再来');
            }
        }
        Db::startTrans();
        try{

            if($task_type == 1){
                //查询该用户之前是否有删除且没有扣费的帖子
                $list = DistributeTaskModer::where(['user_id'=>$this->user['id'],'is_fee_deduction'=>0,'is_del'=>1])->select();
                if($list){
                    $task_price = $this->user['task_price'];
                    //判断用户是否还存在佣金
                    foreach ($list  as $v) {
                        if($task_price >= 1){
                            $task_price -= 1;
                            DistributeTaskModer::where(['id'=>$v['id']])->update(['is_fee_deduction'=>1]);
                            //进行扣除佣金操作
                            User::where(['id'=>$this->user['id']])->update(['task_price'=>$task_price]);
                            //记录佣金日志
                            $arr = [
                                'user_id'=>$this->user['id'],
                                'new_price'=>$task_price,
                                'price'=>-1,
                                'type'=>4,
                                'old_price'=>$task_price+1,
                                'add_time'=>time()
                            ];
                            DistributeTaskLog::insert($arr);
                        }
                    }
                }
                //查询该用户接上个任务是什么时候
                $s_info = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>1])->order('receive_time desc')->find();
                if($s_info && time()-$s_info['receive_time'] < 600){
                    Db::rollback();
                    $this->error('两个任务相隔时间未超过10分钟，请10分钟后再接');
                }
                $where = [
                    'user_id'=>0,
                    'status'=>0,
                    'type'=>$type,
                    'province'=>['in',['',$this->user['province']]],
                    'character_type'=>$this->user['character_type'],
                    //'is_new_user'=>0,
                    'task_type'=>$task_type
                ];
                //if($type == '余享小红书'){
                    //查询该用户一周的所有接单商品类目
                    $category_arr = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>['in',[1,2,3]],'category'=>['neq',0]])->whereTime('receive_time', '-7 days')->column('category');
                    if($category_arr){
                        $where['category'] = ['not in',$category_arr];
                    }
                //}
                // if($s_info && $s_info['category'] && (strtotime(date("Y-m-d",time()))-(3600*24)) < $s_info['receive_time']){
                //     $where['category'] = ['neq',$s_info['category']];
                // }


                // if($this->user['task_price'] == 0){
                //     $is_new_user = DistributeTaskLog::where(['type'=>2,'user_id'=>$this->user['id']])->find();
                //     if(!$is_new_user){
                //     $where['is_new_user'] = 1;
                //     }
                // }
                //打开就是只能接相对应类别任务
                /* if($this->user['id'] !='13438'){
                    $ids = ShopUserCategory::where(['user_id'=>$this->user['id']])->column('category_id');
                    if($ids){
                        $shop_names = Shop::where(['category_id'=>['in',$ids]])->column('name');
                        if($this->user['is_admin'] == 1){
                            $shop_names[] = '苏拉科技';
                        }
                        $where['type'] = ['in',$shop_names];
                    }
                } */
                $listTask = DistributeTaskModer::where($where)->select();
                if(!$listTask){
                    Db::rollback();
                    $this->error('当前任务已领完,请过一会再来查看新任务');
                }
                $info = $listTask[rand(0,count($listTask)-1)];
                //判断是否已经接了该类型任务
                $res = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>['in',[1,2,-1]],'type'=>$type,'task_type'=>$task_type])->whereTime('receive_time', 'today')->count();
                if($res >= 1 && $type != '电事聚小红书'){
                    Db::rollback();
                    $this->error('您已有该类型任务未完成，不可重复领取，请完成后再来领取');
                }
                $res = DistributeTaskModer::where(['id'=>$info['id']])->update(['status'=>1,'user_id'=>$this->user['id'],'receive_time'=>time()]);
                if($res){
                    Db::commit();
                    if($list){
                        $this->success('系统检测到您提前删除了帖子，将会影响你的佣金结算数额');
                    }else{
                        $this->success('接单成功');
                    }
                }else{
                    Db::rollback();
                    $this->error('操作失败');
                }
            }elseif($task_type == 4){
                //查询是否今天是否结果评论任务
                $info = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>['in',[1,2,-1]],'task_type'=>$task_type])->whereTime('receive_time','today')->find();
                if($info){
                    $this->error('您当天已领取过评论任务');
                }
                $where = [
                    'user_id'=>0,
                    'status'=>0,
                    'task_type'=>$task_type
                ];
                $listTask = DistributeTaskModer::where($where)->select();
                if(!$listTask){
                    Db::rollback();
                    $this->error('当前任务已领完,请过一会再来查看新任务');
                }
                $info = $listTask[rand(0,count($listTask)-1)];
                $res = DistributeTaskModer::where(['id'=>$info['id']])->update(['status'=>1,'user_id'=>$this->user['id'],'receive_time'=>time()]);
                if($res){
                    Db::commit();
                    $this->success('接单成功');
                }else{
                    Db::rollback();
                    $this->error('操作失败');
                }
            }elseif($task_type == 5){
                if($this->user['is_material'] == 0){
                    $this->error('权限不足');
                }
                $where = [
                    'user_id'=>0,
                    'status'=>0,
                    'type'=>$type,
                    'task_type'=>$task_type
                ];
                $info = DistributeTaskModer::where($where)->find();
                if(!$info){
                    $this->error('任务错误');
                }
                $res = DistributeTaskModer::where(['id'=>$info['id']])->update(['status'=>1,'user_id'=>$this->user['id'],'receive_time'=>time()]);
                if($res){
                    Db::commit();
                    $this->success('接单成功');
                }else{
                    Db::rollback();
                    $this->error('操作失败');
                }
            }

            
        }catch (Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }
    }

    //获取总数
    public function get_task_sum(){
        $task_sum = DistributeTaskModer::whereTime('receive_time', 'today')->where(['status'=>1])->count();
        $task_sum = ($task_sum*3) + 6;
        $this->success('操作成功',$task_sum);
    }


    //用户删除任务
    public function delTask(){
        $id = $this->request->request('id',0);
        $status = $this->request->request('status',0);
        $info = DistributeTaskModer::where(['user_id'=>$this->user['id'],'id'=>$id,'status'=>['in',['-1','-3','3']]])->find();
        if(!$info){
            $this->error('操作失败');
        }
        if($info['status'] == -3){  //删除任务返回用户金额
            set_shop_task_price($info['id'],1);
        }
        $res = DistributeTaskModer::where(['id'=>$id])->update(['status'=>$status]);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    
    public function getIsTc(){
        $this->error('不弹了');
        $token = $this->request->request('token','');
        if($token){
            $user=User::where(array('token'=>$token))->find();
            if(!$user)  $this->error('不弹了');
            $redis = redis_init();
            $info = $redis->get('getIsTc_'.$user['id']);
            if(!$info){
                $redis->set('getIsTc_'.$user['id'],time());
                $this->success('操作成功');
            }else{
                //判断发布时间
                $time1 = date('Y-m-d',$info);
                $time2 = date('Y-m-d',time());
                if($time1 != $time2){
                    $redis->set('getIsTc_'.$user['id'],time());
                    $this->success('操作成功');
                }
            }
        }
        $this->error('不弹了');
    }
    

    //我的任务列表
    public function userTaskList(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $task_index = $this->request->request('task_index',1);  //1已接单   2待审核  -1已拒绝  3已完成
        $list = DistributeTaskModer::where(['user_id'=>$this->user['id'],'status'=>$task_index])->limit(($page-1)*$pagesize,$pagesize)->order('receive_time desc')->select();
        foreach ($list as &$info) {
            if($info['task_status'] == 'pinglun' || $info['task_status'] == 'comment_num'){
                $info['priceName'] = '¥0.50';
            }else{
                if($info['type'] != '余享小红书'){
                    $info['priceName'] = '¥2.00~¥3.00';
                }else{
                    $info['priceName'] = '¥0~¥3.00';
                }
            }
            $info['time1'] = 0;
            if($info['status'] == 1 && $info['task_type'] < 5){ //已领取状态
                //判断该用户是否已回传链接
                $t = time()-$info['receive_time'];
                if(!$info['user_content']){
                    if($t > 3600){ //已经超时更新订单状态
                        DistributeTaskModer::where(['id'=>$info['id']])->update(['status'=>-2]);
                        $info['status'] = 0;
                    }else{
                        $info['time1'] = 3600 - $t;
                    }
                }else{
                    if(!$info['user_imgs']){
                        if($t >  (3600*36)){ //已经超时更新订单状态
                            DistributeTaskModer::where(['id'=>$info['id']])->update(['status'=>-2]);
                            $info['status'] = 0;
                        }else{
                            $info['time1'] = (3600*36) - $t;
                        }
                    }
                }
            }
            if($task_index == 3){
                $info['complete_time'] = date('Y-m-d H:i:s',$info['complete_time']);
            }
        }

        $this->success('操作成功',$list);
        
    }
    //获取任务规则
    public function question(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',20);
        $where=array('type'=>3,'status'=>1);
        $list=Article::where($where)->order('ord asc')->limit(($page-1)*$pagesize,$pagesize)->select();
        foreach($list as $a=>&$b){
            $b['content']=htmlspecialchars_decode($b['content']);
        }
        $this->success('获取成功',$list);
    }
    
    //录入小红书信息
    public function set_user_message(){
        $gender = $this->request->request('genderS','');
        $age = $this->request->request('age','');
        $interest = $this->request->request('interest','');
        $occupation = $this->request->request('occupation','');
        $gender = $this->request->request('genderS','');
        $address = $this->request->request('address','');
        $address_arr = explode('-',$address);
        if($this->user['is_task_set'] == 0){
            $arr = [
                'is_task_set'=>1,
                'is_task'=>-1,
                'task_time'=>time(),
                'gender'=>$gender,
                'age'=>$age,
                'interest'=>$interest,
                'occupation'=>$occupation,
                'province'=>$address_arr[0],
                'city'=>$address_arr[1],
                'district'=>$address_arr[2],
            ];
            User::where(['id'=>$this->user['id']])->update($arr);
        }
        $this->success('操作成功');
    }
    
    

    //获取任务详情
    public function getInfo(){
        $id = $this->request->request('id',0);
        $type = $this->request->request('type',0);
        if($type){
            $info =  DistributeTaskModer::where(['id'=>$id])->find();
        }else{
            $info =  DistributeTaskModer::where(['user_id'=>$this->user['id'],'id'=>$id])->find();
        }
        if(!$info){
            $this->error('参数错误');
        }
        $info['end_time'] = $info['end_time'] ? date('Y-m-d',$info['end_time']) : '';
        if (strpos($info['imgs'], 'https') === false && strpos($info['imgs'], 'http') === false) {
            $info['imgs'] = str_replace('/uploads', 'https://yuxiangapp.oss-cn-guangzhou.aliyuncs.com/uploads', $info['imgs']);
        }
        $info['imgs_arr'] = explode(',',$info['imgs']);
        // foreach ($info['imgs_arr'] as &$v) {
        //     if (strpos($v, 'https') === false) {
        //         $v = 'https://yuxiangapp.oss-cn-guangzhou.aliyuncs.com'.$v;
        //     }
        // }

        
        

        $info['nickname'] = User::where(['id'=>$info['user_id']])->value('nickname');
        //判断是否是第二天  可以上传了
        if(date('Y-m-d',$info['receive_time'])  != date('Y-m-d',time())){
            $info['is_receive_time'] = 1;
        }else{
            $info['is_receive_time'] = 0;
        }
        $info['receive_time'] = date('Y-m-d H:i:s',$info['receive_time']);
        if($info['task_status'] == 'pinglun' || $info['task_status'] == 'comment_num'){
            $info['priceName'] = '¥0.50';
        }else{
            if($info['type'] != '余享小红书'){
                $info['priceName'] = '¥2.00~¥3.00';
            }else{
                $info['priceName'] = '¥0~¥3.00';
            }
        }

        $info['issue_type'] = '';
        if($info['task_type'] == 5){
            $operation_task = OperationTask::where(['task_id'=>$info['id']])->find();
            if($operation_task){
                if($operation_task['issue_type'] == 1){
                    $info['issue_type'] = '封面1张，内页3-5张，文案300-600字';
                }elseif($operation_task['issue_type'] == 2){
                    $info['issue_type'] = '封面1张，文案300-600字';
                }elseif($operation_task['issue_type'] == 3){
                    $info['issue_type'] = '纯文案300-600字';
                }
                
            }
        }

        // if($info['topic']){
        //     $topic = explode(',',$info['topic']);
        //     $info['topic'] = '#'.implode('#',$topic);
        // }else{
        //     $info['topic'] = '#余享#余享APP';
        // }

        $this->success('操作成功',$info);
    }

    //任务回传
    public function distribute_task_add($id = '',$type = '',$statistics_num = '',$title = '',$imgs = '',$sum = 0){
        if($this->user['task_status'] == -1){
            $this->error('您已被冻结接单资格，请更换账号或联系客服');
        }
        $id = $id ? $id : $this->request->request('id',0);
        $type = $type ? $type : $this->request->request('type',0);
        $statistics_num = $statistics_num ? $statistics_num : $this->request->request('statistics_num','');
        $title = $title ? $title : $this->request->request('title','');
        $content = $this->request->request('content','');
        $imgs = $imgs ? $imgs : $this->request->request('imgs','');
        $info =  DistributeTaskModer::where(['user_id'=>$this->user['id'],'id'=>$id])->find();
        if(!$info){
            $this->error('参数错误');
        }
        if($type == 4){
            $where = ['user_imgs'=>$imgs,'status'=>2];
        }elseif($type == 3){
            $where = ['illegal_img'=>$imgs,'is_illegal'=>1];
        }elseif($type == 5){
            $where = ['user_operation_title'=>$title,'user_content'=>$content,'user_imgs'=>$imgs,'status'=>2];
        }else{
            $where = [
                'user_content'=>$title,
                'ip'=>request()->ip()
            ];
            if($imgs){
                if(!is_numeric($statistics_num)){
                    $this->error('浏览量格式错误');
                }
                if($statistics_num == '' || $statistics_num == 0){
                    $this->error('浏览量格式错误');
                }
                $where = [
                    'user_imgs'=>$imgs,
                    'statistics_num'=>$statistics_num,
                    'status'=>2
                ];
            }else{
                if (strpos($title, 'https://') !== false) {
                    $res = explode('?',$title);
                    if(empty($res[0])){
                        if($sum == 5){
                            $arr = [
                                'user_id'=>$this->user['id'],
                                'user_content'=>$title,
                                'title'=>$info['title'],
                                'content'=>$info['content'],
                                'imgs'=>$info['imgs'],
                                'task_type'=>$info['task_type'],
                                'type'=>$info['type'],
                                'add_time'=>$info['add_time'],
                                'receive_time'=>$info['receive_time'],
                                'product_id'=>$info['product_id'],
                                'character_type'=>$info['character_type'],
                                'cf_content'=>'链接提交错误,请确认后重新提交'
                            ];
                            DistributeTaskCopyLog::insert($arr);
                            $this->error('链接提交错误,请确认后重新提交');
                        }else{
                            return $this->distribute_task_add($id,$type,$statistics_num,$title,$imgs,$sum+1);
                        }
                        
                    }
                    $datas = explode('/',$res[0]);
                }elseif(strpos($title, 'http://') !== false){
                    $res = explode('http://',$title);
                    if(empty($res[1])){
                        if($sum == 5){
                            $arr = [
                                'user_id'=>$this->user['id'],
                                'user_content'=>$title,
                                'title'=>$info['title'],
                                'content'=>$info['content'],
                                'imgs'=>$info['imgs'],
                                'task_type'=>$info['task_type'],
                                'type'=>$info['type'],
                                'add_time'=>$info['add_time'],
                                'receive_time'=>$info['receive_time'],
                                'product_id'=>$info['product_id'],
                                'character_type'=>$info['character_type'],
                                'cf_content'=>'链接提交错误,请确认后重新提交!'
                            ];
                            DistributeTaskCopyLog::insert($arr);
                            $this->error('链接提交错误,请确认后重新提交!');
                        }else{
                            return $this->distribute_task_add($id,$type,$statistics_num,$title,$imgs,$sum+1);
                        }
                    }
                    $res = explode('，',$res[1]);
                    $headers = get_headers('http://'.$res[0]); //获取重定向之后的url
                    foreach ($headers as $v) {
                        if (strpos($v, 'Location') !== false) {
                            $res = explode('?',$v);
                            if(empty($res[0])){
                                if($sum == 5){
                                    $arr = [
                                        'user_id'=>$this->user['id'],
                                        'user_content'=>$title,
                                        'title'=>$info['title'],
                                        'content'=>$info['content'],
                                        'imgs'=>$info['imgs'],
                                        'task_type'=>$info['task_type'],
                                        'type'=>$info['type'],
                                        'add_time'=>$info['add_time'],
                                        'receive_time'=>$info['receive_time'],
                                        'product_id'=>$info['product_id'],
                                        'character_type'=>$info['character_type'],
                                        'cf_content'=>'链接提交错误,请确认后重新提交。'
                                    ];
                                    DistributeTaskCopyLog::insert($arr);
                                    $this->error('链接提交错误,请确认后重新提交。');
                                }else{
                                    return $this->distribute_task_add($id,$type,$statistics_num,$title,$imgs,$sum+1);
                                }
                            }
                            $datas = explode('/',$res[0]);
                        }
                    }
                }
                if(count($datas) < 4){
                    // if($sum == 5){
                    //     $arr = [
                    //         'user_id'=>$this->user['id'],
                    //         'user_content'=>$title,
                    //         'title'=>$info['title'],
                    //         'content'=>$info['content'],
                    //         'imgs'=>$info['imgs'],
                    //         'task_type'=>$info['task_type'],
                    //         'type'=>$info['type'],
                    //         'add_time'=>$info['add_time'],
                    //         'receive_time'=>$info['receive_time'],
                    //         'product_id'=>$info['product_id'],
                    //         'character_type'=>$info['character_type'],
                    //         'cf_content'=>'链接提交错误,请确认后重新提交?'
                    //     ];
                    //     DistributeTaskCopyLog::insert($arr);
                    //     $this->error('链接提交错误,请确认后重新提交?');
                    // }else{
                    //     return $this->distribute_task_add($id,$type,$statistics_num,$title,$imgs,$sum+1);
                    // }
                }else{
                    //查询小红书ID是否重复出现过
                    // $res = DistributeTaskModer::where(['appuid'=>$datas[count($datas)-1]])->find();
                    // if($res){
                    //     $arr = [
                    //         'user_id'=>$this->user['id'],
                    //         'user_content'=>$title,
                    //         'appuid'=>$datas[count($datas)-1],
                    //         'title'=>$res['title'],
                    //         'content'=>$res['content'],
                    //         'imgs'=>$res['imgs'],
                    //         'task_type'=>$res['task_type'],
                    //         'type'=>$res['type'],
                    //         'add_time'=>$res['add_time'],
                    //         'receive_time'=>$res['receive_time'],
                    //         'product_id'=>$res['product_id'],
                    //         'character_type'=>$res['character_type'],
                    //     ];
                    //     DistributeTaskCopyLog::insert($arr);
                    //     $this->error('当前链接涉及重复提交,请确认后再提交,如有问题可联系客服');
                    // }
                    $where['appuid'] = $datas[count($datas)-1];
                }
            }
        }
        $res =  DistributeTaskModer::where(['id'=>$info['id']])->update($where);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('参数错误');
        }
    }

    
    //获取佣金日志
    public function get_withdraw(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $month = $this->request->request('month','');

        $task_price = $this->user['task_price'];
        //查询该用户之前是否有删除且没有扣费的帖子
        /* $list = DistributeTaskModer::where(['user_id'=>$this->user['id'],'is_fee_deduction'=>0,'is_del'=>1])->select();
        if($list){
            //判断用户是否还存在佣金
            foreach ($list  as $v) {
                if($task_price >= 1){
                    $task_price -= 1;
                    DistributeTaskModer::where(['id'=>$v['id']])->update(['is_fee_deduction'=>1]);
                    //进行扣除佣金操作
                    User::where(['id'=>$this->user['id']])->update(['task_price'=>$task_price]);
                    //记录佣金日志
                    $arr = [
                        'user_id'=>$this->user['id'],
                        'new_price'=>$task_price,
                        'price'=>-1,
                        'type'=>4,
                        'old_price'=>$task_price+1,
                        'add_time'=>time()
                    ];
                    DistributeTaskLog::insert($arr);
                }
            }
        } 
        $start_time=strtotime($month.'-01');
		$end_time=strtotime($month.'-01 +1 month');
		$add_time=array('between',array($start_time,$end_time));
        $thismonth_1=strtotime(date("Y-m-01 00:00:01"));
		$thismonth_2=strtotime('+1 month',$thismonth_1);
        $thismonth=array('between',array($thismonth_1,$thismonth_2));*/
		$rose['yue']=$task_price;
		$rose['month_in']=DistributeTaskLog::where(array('user_id'=>$this->user['id'],'price'=>['>',0]))->sum('price');	
		$rose['month_out']=0-DistributeTaskLog::where(array('user_id'=>$this->user['id'],'price'=>['<',0]))->sum('price');	
		$rose['month_log']=DistributeTaskLog::where(array('user_id'=>$this->user['id']))->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
		foreach($rose['month_log'] as &$v){
			$v['add_time']=date("Y-m-d H:i:s",$v['add_time']);
            $v['status'] = 1;
            $v['handingfee'] = 0;
            if($v['type'] == 1){
                $v['content'] = '任务佣金';
            }elseif($v['type'] == 2){
                $v['content'] = '提现金额';
                //查询该笔提现状态
                $info = Withdraw::where(['id'=>$v['withdraw_id'],'user_id'=>$this->user['id']])->order('id desc')->find();
                if($info && $info['status'] == 'created'){
                    $v['status'] = '2';
                }elseif($info && $info['status'] == 'rejected'){
                    $v['status'] = '-1';
                }
                $v['handingfee'] = $info['handingfee'];
            }elseif($v['type'] == 3){
                $v['content'] = '拒绝提现返还佣金';
            }elseif($v['type'] == 4){
                $v['content'] = '违规删帖惩罚';
            }elseif($v['type'] == 5){
                $v['content'] = '邀请奖励';
            }
		}
        $this->success('操作成功',$rose);
    }

    //获取提现规则配置
    public function getConfirmData(){
        $name = $this->request->request('name','');
        $value = PayConfig::where(['name'=>$name])->value('value');
        if($value){
            $data = json_decode($value,true);
            $data['withdraw_rule'] = explode(',',$data['withdraw_rule']);
            $data['task_rule'] = explode(',',$data['task_rule']);
            $this->success('获取成功',$data);
        }else{
            $this->error('获取失败');
        }
    }

    //申请提现
    public function send_withdraw(){
        $price = $this->request->request('price',0);
        $imgs = $this->request->request('imgs','');

        //查询该用户账号余额
        Db::startTrans();
        try{
            $info =  User::where(['id'=>$this->user['id']])->find();
            if($info['task_price'] != $price){
                Db::rollback();
                $this->error('用户余额异常，请联系客服');
            }
            //判断该用户是否是首次提现
            $res = Withdraw::where(['user_id'=>$this->user['id'],'status'=>['in',['created','successed']]])->find();
            if($res && $this->user['task_status'] == 1){  
                //不是首次提现需判断是否达到提现要求
                $PayConfig = get_task_config();
                if($PayConfig['withdraw_min_price'] > $price){
                    $this->error('最低提现为'.$PayConfig['withdraw_min_price'].'元,您账户佣金不足');
                }
            }
            $money = bcmul($price, 0.99, 2);
            $handingfee = bcsub($price, $money, 2);
            $arr = [
                'user_id'=>$this->user['id'],
                'money'=>$money,
                'handingfee'=>$handingfee,
                'imgs'=>$imgs,
                'orderid'=>date("YmdHis").rand(1000,9999),
                'add_time'=>time()
            ];
            $res = Withdraw::insertGetId($arr);
            if($res){
                //添加日志
                $arr = [
                    'user_id'=>$this->user['id'],
                    'new_price'=>$money,
                    'old_price'=>0,
                    'price'=>$money*-1,
                    'handingfee'=>$handingfee*-1,
                    'type'=>2,
                    'add_time'=>time(),
                    'withdraw_id'=>$res
                ];
                DistributeTaskLog::insert($arr);

                //扣除用户账户余额
                User::where(['id'=>$this->user['id']])->update(['task_price'=>0]);

                Db::commit();
                $this->success('申请成功');
            }else{
                Db::rollback();
                $this->error('操作失败');
            }
        }catch (Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }
        
    }

    //申请成为团长
    public function send_distribute(){
        $res = User::where(['id'=>$this->user['id']])->update(['is_task'=>1,'task_time'=>time()]);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }


    
}